<template>
  <div class="page-content">
    <div class="header">
      <h3>画面参数管理</h3>
    </div>

    <div class="actions-bar">
      <el-row :gutter="20">
        <el-col :span="24" class="action-buttons">
          <el-button type="primary" @click="openDialog()" v-ripple>添加参数</el-button>
          <el-button @click="refreshList" v-ripple>刷新列表</el-button>
        </el-col>
      </el-row>
    </div>

    <div class="bitrate-table">
      <el-table
        v-loading="loading"
        :data="bitrateList"
        stripe
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="画质名称" min-width="120" />
        <el-table-column prop="max_size" label="最大分辨率" min-width="120">
          <template #default="scope">{{ scope.row.max_size }}p</template>
        </el-table-column>
        <el-table-column prop="video_bite_rate" label="视频码率(bps)" min-width="150">
          <template #default="scope">{{ formatBitrate(scope.row.video_bite_rate) }}</template>
        </el-table-column>
        <el-table-column prop="audio_bite_rate" label="音频码率(bps)" min-width="150">
          <template #default="scope">{{ formatBitrate(scope.row.audio_bite_rate) }}</template>
        </el-table-column>
        <el-table-column prop="fps" label="帧率(fps)" min-width="120" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div style="display: flex; gap: 5px;">
              <el-button size="small" type="primary" @click="openDialog(scope.row)" plain>编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" plain>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="isEdit ? '编辑画面参数' : '添加画面参数'" 
      v-model="dialogVisible" 
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="画质名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入画质名称" />
        </el-form-item>
        <el-form-item label="最大分辨率" prop="max_size">
          <el-select v-model="form.max_size" placeholder="请选择分辨率">
            <el-option label="360p" :value="360" />
            <el-option label="480p" :value="480" />
            <el-option label="720p" :value="720" />
            <el-option label="1080p" :value="1080" />
            <el-option label="1440p" :value="1440" />
            <el-option label="2160p" :value="2160" />
          </el-select>
        </el-form-item>
        <el-form-item label="视频码率" prop="video_bite_rate">
          <el-input-number 
            v-model="form.video_bite_rate" 
            :min="1" 
            :step="1000" 
            controls-position="right"
            style="width: 100%"
          />
          <div class="form-tip">单位: bps</div>
        </el-form-item>
        <el-form-item label="音频码率" prop="audio_bite_rate">
          <el-input-number 
            v-model="form.audio_bite_rate" 
            :min="1" 
            :step="1000" 
            controls-position="right"
            style="width: 100%"
          />
          <div class="form-tip">单位: bps</div>
        </el-form-item>
        <el-form-item label="帧率" prop="fps">
          <el-input-number 
            v-model="form.fps" 
            :min="1" 
            :max="120" 
            controls-position="right"
            style="width: 100%"
          />
          <div class="form-tip">单位: fps</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getBitrateList, 
  addBitrate, 
  updateBitrate, 
  deleteBitrate,
  type BitrateParams 
} from '@/Newapi/device'

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 画面参数列表
const bitrateList = ref<BitrateParams[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive<BitrateParams>({
  name: '',
  max_size: 720,
  video_bite_rate: 500000,
  audio_bite_rate: 128000,
  fps: 25
})
const formRef = ref()

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入画质名称', trigger: 'blur' }],
  max_size: [{ required: true, message: '请选择最大分辨率', trigger: 'change' }],
  video_bite_rate: [{ required: true, message: '请输入视频码率', trigger: 'blur' }],
  audio_bite_rate: [{ required: true, message: '请输入音频码率', trigger: 'blur' }],
  fps: [{ required: true, message: '请输入帧率', trigger: 'blur' }]
}

// 格式化比特率显示
const formatBitrate = (bitrate: number): string => {
  if (bitrate >= 1000000) {
    return `${(bitrate / 1000000).toFixed(2)} Mbps`
  } else if (bitrate >= 1000) {
    return `${(bitrate / 1000).toFixed(2)} Kbps`
  } else {
    return `${bitrate} bps`
  }
}

// 获取画面参数列表
const fetchBitrateList = async () => {
  loading.value = true
  try {
    const result = await getBitrateList()
    if (result.code === 200) {
      bitrateList.value = result.data
    } else {
      ElMessage.error(result.msg || '获取画面参数列表失败')
    }
  } catch (error) {
    console.error('获取画面参数列表失败:', error)
    ElMessage.error('获取画面参数列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  fetchBitrateList()
  ElMessage.success('画面参数列表已刷新')
}

// 打开对话框
const openDialog = (data?: BitrateParams) => {
  isEdit.value = !!data
  if (data) {
    // 编辑模式，填充表单数据
    Object.assign(form, data)
  } else {
    // 添加模式，重置表单
    Object.assign(form, {
      name: '',
      max_size: 720,
      video_bite_rate: 500000,
      audio_bite_rate: 128000,
      fps: 25
    })
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    let result
    if (isEdit.value && form.id) {
      // 编辑模式
      result = await updateBitrate(form.id, form)
    } else {
      // 添加模式
      result = await addBitrate(form)
    }
    
    if (result.code === 200) {
      ElMessage.success(isEdit.value ? '画面参数已更新' : '画面参数已添加')
      dialogVisible.value = false
      fetchBitrateList() // 刷新列表
    } else {
      ElMessage.error(result.msg || (isEdit.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error(isEdit.value ? '更新画面参数失败:' : '添加画面参数失败:', error)
    ElMessage.error(isEdit.value ? '更新失败，请重试' : '添加失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 删除画面参数
const handleDelete = (data: BitrateParams) => {
  if (!data.id) {
    ElMessage.warning('参数ID不存在')
    return
  }
  
  ElMessageBox.confirm(`确定要删除画面参数"${data.name}"吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const result = await deleteBitrate(data.id!)
        if (result.code === 200) {
          ElMessage.success('画面参数已删除')
          fetchBitrateList() // 刷新列表
        } else {
          ElMessage.error(result.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除画面参数失败:', error)
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 页面加载时获取数据
onMounted(() => {
  fetchBitrateList()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .actions-bar {
    margin: 20px 0;
    
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }

  .bitrate-table {
    margin-bottom: 20px;
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.2;
    margin-top: 4px;
  }
}
</style> 